package com.treasure.web.service;

import com.treasure.common.utils.RandomIdGenerator;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author sunhongmin
 * @date 2024/1/1 21:58
 * @description
 */
@Service
public class LocalFileRepository {
    public static final String BASE_STORE_PATH = System.getProperty("user.dir") + File.separator + "data" + File.separator + "file";
    public static final String SERVER_URI = "/file/rep";

    /**
     * 文件上传
     *
     * @param file
     * @param purpose 用途，用作文件夹分类
     * @return 访问链接
     * @throws IOException
     */
    public String uploadFileStore(MultipartFile file, String purpose) throws IOException {
        String traceId = RandomIdGenerator.traceId();
        String storePath = File.separator + purpose + File.separator + traceId + File.separator + file.getOriginalFilename();
        File createFile = new File(BASE_STORE_PATH + storePath);
        if (!createFile.exists()) {
            // 递归创建目录
            createFile.mkdirs();
        }
        file.transferTo(createFile);
        return SERVER_URI + storePath;
    }
}
